<?php

/* 访问控制 */
defined('IN_ECTOUCH') or die('Deny Access');

class ArticleController extends CommonController {

    private $size = 10;
    private $page = 1;
    private $cat_id = 0;
    private $keywords = '';
    private $accessTokenCachename = '';
    private $jsApiTicketCachename = '';

    public function __construct() {
        parent::__construct();
        $this->cat_id = intval(I('get.id'));

        $key = md5($this->appId."-".$this->appSecret);
        $this->accessTokenCachename = 'rg_weixin_access_token_'.$key;
        $this->jsApiTicketCachename = 'rg_weixin_js_api_ticket_'.$key;

		$this->assign('pc_url', C('shop_url'));
    }

    /* ------------------------------------------------------ */

    //-- 文章分类
    /* ------------------------------------------------------ */
    public function index() {
        $cat_id = intval(I('get.id'));
        $cat = model('Article')->article_categories_tree($cat_id);
        $this->assign('article_categories', $cat); //文章分类树
        $this->display('article_cat.dwt');
    }

    /* ------------------------------------------------------ */

    //-- 文章列表
    /* ------------------------------------------------------ */
    public function art_list() {
        $this->parameter();
        $this->assign('keywords', $this->keywords);
        $this->assign('id', $this->cat_id);
		if(in_array($this->cat_id, array(23))){
			$this->display('share_list.dwt');
		}else{
			$this->display('article_list.dwt');
		}
    }

    /**
     * 文章列表异步加载
     */
    public function asynclist() {
        $this->parameter();
        $asyn_last = intval(I('post.last')) + 1;
        $this->size = I('post.amount');
        $this->page = ($asyn_last > 0) ? ceil($asyn_last / $this->size) : 1;
        $list = model('ArticleBase')->get_cat_articles($this->cat_id, $this->page, $this->size, $this->keywords);
        foreach ($list as $key => $value) {
            $this->assign('article', $value);
            $sayList [] = array(
                'single_item' => ECTouch::view()->fetch('library/asynclist_info.lbi')
            );
        }
        die(json_encode($sayList));
        exit();
    }

    /* ------------------------------------------------------ */

    //-- 文章详情
    /* ------------------------------------------------------ */
    public function info() {
        /* 文章详情 */
        $article_id = intval(I('get.aid'));
        $article = model('Article')->get_article_info($article_id);
        $this->assign('article', $article);
		
		$share_info = $this->get_jssdk_config();
		$share_info['share_title']	= $article['title'];
		$share_info['share_desc']	= $article['description'];
		$share_info['file_url']		= C('shop_url').$article['file_url'];
		$this->assign("share_info", $share_info);

        $this->display('article_info.dwt', $cache_id);
    }
    public function share() {
		if(!$_SESSION ['user_id']) die(json_encode(3));
		$article_id = intval(I('post.aid'));
		$fs_article = $this->model->table('Article')->field("cat_id, title")->where( array('article_id'=>$article_id) )->find();
		if(in_array($fs_article['cat_id'], array(23))){
			$fs_num = $this->model->table('account_log')->where( "fs_type=1 and user_id = '".$_SESSION ['user_id']."' and FROM_UNIXTIME(change_time,'%Y-%m-%d') ='".date('Y-m-d')."'" )->count();
			if($fs_num < 2){
				$res =  model('ClipsBase')->log_account_change($_SESSION['user_id'], 0, 0, 0, C('share_integral'), "分享文章 《".$fs_article['title']."》 获得积分", 99, 1);
				if($res){
					die(json_encode(1));
				}else{
					die(json_encode(0));
				}
			}else{
				die(json_encode(2));
			}
		}
	}

    /**
     * 处理参数便于搜索商品信息
     */
    private function parameter() {
        // 如果分类ID为0，则返回总分类页
        $page_size = C('page_size');
        $this->size = intval($page_size) > 0 ? intval($page_size) : 10;
        $this->cat_id = intval(I('request.id'));
        $this->keywords = I('request.keywords');
        /* 排序、显示方式以及类型 */
        $default_display_type = C('show_order_type') == '0' ? 'list' : (C('show_order_type') == '1' ? 'grid' : 'album');
        $default_sort_order_method = C('sort_order_method') == '0' ? 'DESC' : 'ASC';
        $default_sort_order_type = C('sort_order_type') == '0' ? 'goods_id' : (C('sort_order_type') == '1' ? 'shop_price' : 'last_update');
        setcookie('ECS[display]', $display, gmtime() + 86400 * 7);
    }
	
	function get_jssdk_config() {
        $jsapiTicket	= $this->get_js_api_ticket();
        $nonceStr		= create_nonce_str();
        $timestamp		= time();
        $url			= $this->get_url();
        
        $string			= "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature		= sha1($string);

        $signConfig = array( "appId" => $this->appId, "nonceStr" => $nonceStr, "timestamp" => $timestamp, "signature" => $signature, "rawString" => $string, "share_url" => $url );
        return $signConfig; 
    }

	function get_access_token(){
		$cache_file = "data/rg_cache/cache_".$this->accessTokenCachename.".php";
		$rg_cache = include $cache_file;
        if(!file_exists( $cache_file ) || ($rg_cache['cache_time'] + 600 < time())){
            $get_access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appId."&secret=".$this->appSecret;
            $return = get_html($get_access_token_url);
            if(!empty($return)){
                $content = json_decode($return, true);
                if(is_array($content) && !empty($content) && isset($content['access_token']) && !empty($content['access_token'])){
                    $rg_cache['access_token'] = $content['access_token'];
                }
            }

			$cachedata['access_token']	= $rg_cache['access_token'];
			$cachedata['cache_time']	= time();
            file_put_contents($cache_file, "<?php\treturn " . var_export($cachedata, true) . ";?>");
            
			$rg_cache = include $cache_file;
        }

        return $rg_cache['access_token'];
    }

	function get_js_api_ticket(){
        $cache_file = "data/rg_cache/cache_".$this->jsApiTicketCachename.".php";
		$rg_cache = include $cache_file;
        if(!file_exists( $cache_file ) || ( $rg_cache['cache_time'] + 3600 < time() )){
            $access_token = $this->get_access_token();
            $get_js_api_ticket = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token={$access_token}";
            $return = get_html($get_js_api_ticket);
            if(!empty($return)){
                $content = json_decode($return, true);
                if(is_array($content) && !empty($content) && isset($content['ticket']) && !empty($content['ticket'])){
                    $rg_cache['js_api_ticket'] = $content['ticket'];
                }
            }
			
			$cachedata['js_api_ticket']	= $rg_cache['js_api_ticket'];
			$cachedata['cache_time']	= time();
            file_put_contents($cache_file, "<?php\treturn " . var_export($cachedata, true) . ";?>");

            $rg_cache = include $cache_file;
        }
        return $rg_cache['js_api_ticket'];
    }

	function get_url($is_canshu = 1){
		$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$url = "$protocol$_SERVER[HTTP_HOST]".($is_canshu == 1 ? $_SERVER[REQUEST_URI] : '');
		
		return $url;
	}
}